package com.jmb.apiplatform.controller;


import com.alibaba.fastjson.JSON;
import com.jmb.apiplatform.common.PageResult;
import com.jmb.apiplatform.common.Result;
import com.jmb.apiplatform.exception.ValidException;
import com.jmb.apiplatform.pojo.UserDao;
import com.jmb.apiplatform.pojo.UserLoginLogDao;
import com.jmb.apiplatform.pojo.UserPwdTO;
import com.jmb.apiplatform.pojo.UserVO;
import com.jmb.apiplatform.service.RoleService;
import com.jmb.apiplatform.service.UserLoginLogService;
import com.jmb.apiplatform.service.UserService;
import com.jmb.apiplatform.util.JwtUtils;
import com.jmb.apiplatform.util.NoUtil;
import com.jmb.apiplatform.util.RedisUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static com.jmb.apiplatform.constant.Constants.TOKEN_PREFIX;

@Tag(name = "用户接口")
@RestController
@RequestMapping("/user")
@Slf4j
public class    UserController {
    @Autowired
    UserService userService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    UserLoginLogService userLoginLogService;
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    RoleService roleService;

    // 用户列表
    @Operation(summary = "用户列表")
    @GetMapping("/list")
    public Result list( UserVO userVO){
        log.info("传进来的user是{}", JSON.toJSONString(userVO));
        PageResult<UserDao> pageResult = userService.listUser(userVO);
        return Result.success(pageResult);
    }

    // 注册用户
    @Operation(summary = "用户注册")
    @ResponseBody
    @PostMapping("/register")
    public Result registerUserInfo(@RequestBody UserDao userDao) throws ValidException {
        userService.registerUserInfo(userDao);
        return Result.success("注册成功");
    }

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result LoginUser(@RequestBody UserDao userDao, HttpServletRequest request ) throws ValidException {
        if (userDao.getUsername()==null || userDao.getUsername().trim().isEmpty()){
            return Result.fail("账号不能为空");
        }
        if (userDao.getPassword()==null || userDao.getPassword().trim().isEmpty()){
            return Result.fail("密码不能为空");
        }

        UserDao loginUserDao = userService.loginUser(userDao);
        if (loginUserDao !=null){
            Integer userId = loginUserDao.getUserId();
            HashMap<String, Object> tokenMap = new HashMap<>();
            tokenMap.put("userid", userId);
            tokenMap.put("username", loginUserDao.getUsername());
            String token = jwtUtils.generateJwt(tokenMap);
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("userId", userId);
            hashMap.put("username", loginUserDao.getUsername());
            hashMap.put("name", loginUserDao.getName());
            hashMap.put("enable", loginUserDao.getEnable());
            hashMap.put("token",token);
            Integer roleId = loginUserDao.getRoleId();
            // 这个地方写入权限
            List<String> permission = roleService.readPermission(roleId);
            hashMap.put("permission",permission);
            log.info("传入的userid是{}",userId);
            redisUtil.set(TOKEN_PREFIX+userId,hashMap,60*60*24);
            // 登录日志写入
            UserLoginLogDao userLog = new UserLoginLogDao();
            userLog.setUserId(loginUserDao.getUserId());
            userLog.setUsername(loginUserDao.getUsername());
            userLog.setIp(userLoginLogService.getUserIp(request));
            userLog.setLoginTime(new Date());
            userLoginLogService.insertUserLoginLog(userLog);
            // 查询
            return Result.success("登录成功",hashMap);
        }
        else {
            return Result.fail("账号或密码错误");
        }

    }

    @Operation(summary = "用户新增")
    @PostMapping("/sava")
    public Result saveUser(@RequestBody UserDao userDao) throws ValidException {
        userService.saveUser(userDao);

        return Result.success("新增成功");
    }


    @Operation(summary = "用户退出")
    @GetMapping("/logout")
    public Result logout(@RequestHeader("Token") String token){
        userService.LoginOut(token);
        return Result.success("退出成功");
    }

    @Transactional
    @Operation(summary = "用户删除")
    @GetMapping("/delete")
    public Result deleteUser(HttpServletRequest request,Integer userId) throws ValidException {
        userService.removeUserById(request,userId);
        return Result.success("删除成功");
    }
    @Operation(summary = "修改密码")
    @PostMapping("/pwd/change")
    public Result changePwd(HttpServletRequest request, @RequestBody UserPwdTO userPwdTO) throws ValidException {
        String oldPwd = userPwdTO.getOldPwd();
        String newPwd = userPwdTO.getNewPwd();
        userService.changePwd(request,oldPwd,newPwd);
        return Result.success("更新成功");
    }
    @Operation(summary = "密码重置")
    @GetMapping("/pwd/reset/{userId}")
    public Result pwdRest(@PathVariable Integer userId) throws ValidException {
        userService.pwdReset(userId, NoUtil.DEFAULT_PWD);
        return  Result.success("操作成功");
    }

    @Operation(summary = "查找用户")
    @GetMapping("/info/{userId}")
    public Result infoUserById(@PathVariable Integer userId) throws ValidException {
        UserDao userDao = userService.infoUserById(userId);
        return Result.success(userDao);
    }

    @Operation(summary = "用户修改")
    @PostMapping("/update")
    public Result updateUser(@RequestBody UserDao userDao) throws ValidException {
        userService.modifyUser(userDao);
        return Result.success("更新成功");
    }

}
